package com.bagua.sbbcshop.admincontroller;

import com.bagua.sbbcshop.auth.Token;
import com.bagua.sbbcshop.auth.TokenManager;
import com.bagua.sbbcshop.config.ApiConfig;
import com.bagua.sbbcshop.tool.JDKencMD5_32;
import com.bagua.sbbcshop.tool.StringNumUtil;
import com.bagua.sbbcshop.vo.BasicResponse;
import com.bagua.sbbcshop.vo.UserResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import uw.dm.DAOFactory;
import uw.dm.TransactionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * 账户管理相关接口
 *
 * @author xhou
 */

@Api(value = "User", tags = "账户管理相关接口", description = "账户管理相关接口")
@RestController
@RequestMapping(value = "/api/a/user")
public class UserController {
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private HttpServletRequest request;

    private Logger logger= LoggerFactory.getLogger(UserController.class);

    DAOFactory dao = DAOFactory.getInstance();


    /**
     * 商户登录
     * @param userId    登录账户
     * @param password  登录密码
     * @return UserResponse 响应体
     * @throws IOException
     * @throws TransactionException
     */
    @ApiOperation(value = "商户登录", notes = "商户登录")
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public BasicResponse<UserResponse> login(@RequestParam(name = "userId", required = false) @ApiParam("登录账户，手机号") String userId,
                                             @RequestParam(name = "password") @ApiParam("登录密码") String password){
        UserResponse userResponse= null;
        try {
            if(StringUtils.isBlank(password)){
                return BasicResponse.failure("密码不正确！");
            }
            //清除原有身份信息
            tokenManager.cleanToken(request);

            userResponse = null;
            String sql="select * from user_info where state=1 ";
            StringBuilder sbsql=new StringBuilder();
            List<Object> params = new ArrayList<>();
            sbsql.append(" and login_id=?");
            params.add(userId);
            if(StringNumUtil.chkInt(userId)){
                sbsql.append(" and mobile=?");
                params.add(userId);
            }
            userResponse= dao.queryForSingleObject(ApiConfig.DBLINK,UserResponse.class,sql+sbsql.toString(),params.toArray());
            if(JDKencMD5_32.getMD5Str(password).equals(userResponse.getPassword())){
                Token token = new Token();
                token.setUserId(userResponse.getUserId());
                token.setLoginId(userResponse.getLoginId());
                token.setManager(userResponse.getManager());
                token.setMobile(userResponse.getMobile());
                token.setOpenid(userResponse.getOpenid());
                token.setUserName(userResponse.getUserName());
                token.setTimein(System.currentTimeMillis());

                String tokenKey = tokenManager.createToken(token);
                response.setHeader(ApiConfig.JWT_TOKEN_HEADER_PARAM,
                        ApiConfig.JWT_TOKEN_HEADER_PREFIX + tokenKey);
                return BasicResponse.success("登陆成功",userResponse);
            }
        } catch (TransactionException e) {
            logger.error(e.getMessage(),e);
        }
         return BasicResponse.failure("登陆失败！");
    }


}
